package cn.taskservice.jwt.config;

import cn.taskservice.jwt.service.TokenStoreService;
import cn.taskservice.jwt.serviceImpl.LocalCacheTokenStoreServiceImpl;
import cn.taskservice.jwt.utils.JwtTokenUtil;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.RequiredArgsConstructor;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;

@Configuration
@EnableConfigurationProperties(JwtPropertiesConfig.class)
@RequiredArgsConstructor
@ConditionalOnProperty(name = "task-job.jwt.enabled", havingValue = "true", matchIfMissing = true)
public class JwtAutoConfiguration {

    private final JwtPropertiesConfig jwtProperties;
    private final StringRedisTemplate redisTemplate;

    /**
     * Redis 订阅监听容器
     */
    @Bean
    @ConditionalOnMissingBean
    public RedisMessageListenerContainer redisMessageListenerContainer(RedisConnectionFactory factory) {
        RedisMessageListenerContainer container = new RedisMessageListenerContainer();
        container.setConnectionFactory(factory);
        return container;
    }

    @Bean
    public TokenStoreService tokenStoreService(RedisMessageListenerContainer container) {
        return new LocalCacheTokenStoreServiceImpl(redisTemplate, jwtProperties, container);
    }

    @Bean
    public JwtTokenUtil jwtTokenUtil(TokenStoreService tokenStoreService, ObjectMapper objectMapper) {
        return new JwtTokenUtil(jwtProperties, objectMapper, tokenStoreService);
    }
}
